package com.anywhere.freightman.order.controller;

import com.anywhere.freightman.common.ContextKeys;
import com.anywhere.freightman.common.annotation.Permission;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.user.Account;
import com.anywhere.freightman.common.enumeration.WaybillStatus;
import com.anywhere.freightman.common.ex.CustomException;
import com.anywhere.freightman.order.model.GoodsModel;
import com.anywhere.freightman.order.model.WaybillModel;
import com.anywhere.freightman.order.service.IGoodsService;
import com.anywhere.freightman.order.service.IWaybillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("goods")
@Api("货物")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IWaybillService waybillService;

    @Permission(code = "PROJECT")
    @PostMapping("{orderNo}")
    @ApiOperation("添加货物")
    public ReturnResp getListByOrderNo(HttpServletRequest httpRequest,
                                       @PathVariable("orderNo") String orderNo,
                                       @RequestBody GoodsModel request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);

        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !account.getCompanyId().equals(waybill.getCompanyId())) {
            throw new CustomException("订单信息不存在");
        }

        /*if (!waybill.getStatus().equals(WaybillStatus.CREATED)) {
            throw new CustomException("运单已经开始处理，不能中途添加货物");
        }*/

        goodsService.insert(request);
        return ReturnResp.buildOk(request);
    }

    @Permission(code = "PROJECT")
    @DeleteMapping("{orderNo}")
    @ApiOperation("删除货物")
    public ReturnResp remove(HttpServletRequest httpRequest,
                             @PathVariable("orderNo") String orderNo,
                             @RequestParam("goodsId") Long goodsId) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);

        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !account.getCompanyId().equals(waybill.getCompanyId())) {
            throw new CustomException("订单信息不存在！");
        }
        /*if (!waybill.getStatus().equals(WaybillStatus.CREATED)) {
            throw new CustomException("运单已经开始处理，不能中途添加货物！");
        }*/
        GoodsModel model = goodsService.getById(goodsId);
        if (model != null) {
            goodsService.delete(model);
        }
        return ReturnResp.buildOk();
    }
}
